import { ControlType as TYPE } from "@components";
import { Button, Space, message, Popconfirm,Spin } from "antd"
import { useMainContext } from '@contexts/MainContext'
import { deleteCfgNoticeById, findTemplateByUnitCode } from "@apis/informConfigApi";
import { RULE_REQUIRED } from "@rules";
import { useState, useRef } from "react";

const fields = [
    { name: 'unitCode', label: '归属机构', controlType: TYPE.SELECT, codeKey: 'userAuthUnits' },
    { name: 'cfgRiskRank', label: '风险等级', controlType: TYPE.SELECT, codeKey: 'RiskGradeType' },
    { name: 'status', label: '状态', controlType: TYPE.SELECT, codeKey: 'status' }
]

const del = (row, queryFormRef) => {
    return new Promise(async (resolve, reject) => {
      const {data, error} = await deleteCfgNoticeById(row.emerNoticeId)
      if (error) return reject(error)
      resolve()
      queryFormRef.current.submit()
      message.success(data)
    })
  };

const GetColumns = ( queryFormRef, edit ) => {
    const { isButtomShow } = useMainContext()

    return [
        { title: '归属机构', dataIndex: 'unitName', key: 'unitName', open: true },
        { title: '风险等级', dataIndex: 'cfgRiskRankDesc', key: 'cfgRiskRankDesc', open: true },
        { title: '通知角色', dataIndex: 'roleNames', key: 'roleNames', open: true },
        { title: '通知模板', dataIndex: 'title', key: 'title', open: true },
        { title: '通知内容', dataIndex: 'content', key: 'content', open: true },
        { title: '状态', dataIndex: 'statusName', key: 'statusName', open: true },
        {
            title: "操作",
            dataIndex: 'operationCol',
            key: 'operationCol',
            open: true,
            fixed: 'right',
            render: (_, record) => {
                return (
                    <Space>
                        {isButtomShow('430203') && <Button type="primary" onClick={() => edit(record)}>编辑</Button>}
                        {(isButtomShow('430204') && record.status === '1') && <Popconfirm title="是否确定删除该区域？" onConfirm={() => del(record, queryFormRef)}>
                          <Button type="primary" danger>删除</Button>
                        </Popconfirm>}
                    </Space>
                )
            }
        }
    ]
}

const setTemplateContent = async (value, templates=[], modalFormRef) => {
  if (!value) return
  const newContent = templates.find(item => item.value === value)?.content
  modalFormRef.current?.setFieldValue('content', newContent)
}

const useModalFields = (getTemplateList) => {
  const modalFormRef = useRef("modalFormRef");

  const GetModalFields = (templates, labelLoading, disabled=false, setFields) => {
    const selectConfig = (name, label, codeKey) => {
      return {
        name,
        label,
        codeKey,
        controlType: TYPE.SELECT,
        allowClear: true,
        showSearch: true,
        optionFilterProp: "children",
        filterOption: (input, option) => option.children.toLowerCase()?.includes(input.toLowerCase()),
        notFoundContent: labelLoading ? <Spin size="small" /> : null,
      }
    }

    const noticesTempType = modalFormRef.current?.getFieldValue?.('tempType')

    return [
      { 
          ...selectConfig('unitCode','影响机构','userAuthUnits'), rules: [RULE_REQUIRED],
          disabled: disabled,
          onSelect: (value, option) => {
            if (!option?.value) return
            modalFormRef.current?.setFieldsValue({ ...modalFormRef.current?.getFieldValue(), msgTempId: undefined, content: null })
          },
          onClear: () => {
            modalFormRef.current?.setFieldsValue({ ...modalFormRef.current?.getFieldValue(), msgTempId: undefined, content: null })
          }
       },
      { name: 'cfgRiskRank', label: '风险等级', controlType: TYPE.SELECT, codeKey: 'RiskGradeType', disabled, rules: [RULE_REQUIRED] },
      { name: 'roleIds', label: '通知角色', controlType: TYPE.SELECT, codeKey: 'emerRoles', rules: [RULE_REQUIRED], selectmode: "multiple", },
      { 
        name:'tempType', label:'通知模板类型', controlType:TYPE.SELECT, codeKey:'noticesTempType', rules: [RULE_REQUIRED],
        onChange: () => {
          setFields(GetModalFields(templates, labelLoading, disabled, setFields))
        }
      },

      noticesTempType === 'interior' ? {
        options: templates,
        ...selectConfig('msgTempId','通知模板'),
        rules: [RULE_REQUIRED],
        onFocus: () => getTemplateList(),
        onSelect: value => setTemplateContent(value, templates, modalFormRef)
      }: null,
      noticesTempType === 'interior' ? { name: 'content', label: "通知内容", controlType: TYPE.TEXTAREA, disabled:true, style: { height: 200 } } : null,
      { name: 'status', label: '状态', controlType: TYPE.SELECT, codeKey: 'status', rules: [RULE_REQUIRED] }
    ].filter(_ => _)
  }

    return {
      modalFormRef,
      GetModalFields,
    }
};


export const GetModalFields = () => {
  const [isDisabled, setIsDisabled] = useState(false)
  const modalFormRef = useRef("modalFormRef");

  const [labelLoading, setLabelLoading] = useState(false)
  const [templates, setTemplates] = useState([])
  const getTemplateList = async () => {
    setTemplates([])
    const unitCode = modalFormRef.current?.getFieldValue('unitCode')
    if (!unitCode) return message.error('请先选择影响机构')

    setLabelLoading(true)
    const newTemplates = await findTemplateByUnitCode(unitCode)
    setLabelLoading(false)
    setTemplates(newTemplates)
  }

  const selectConfig = (name, label, codeKey) => {
    return {
      name,
      label,
      codeKey,
      controlType: TYPE.SELECT,
      allowClear: true,
      showSearch: true,
      optionFilterProp: "children",
      filterOption: (input, option) => option.children.toLowerCase()?.includes(input.toLowerCase()),
      notFoundContent: labelLoading ? <Spin size="small" /> : null,
    }
  }

  const modalFields = (isInterior, setIsInterior) => {
    
    return [
      { 
          ...selectConfig('unitCode','影响机构','userAuthUnits'), rules: [RULE_REQUIRED],
          disabled: isDisabled,
          onSelect: (value, option) => {
            if (!option?.value) return
            modalFormRef.current?.setFieldsValue({ ...modalFormRef.current?.getFieldValue(), msgTempId: undefined, content: null })
          },
          onClear: () => {
            modalFormRef.current?.setFieldsValue({ ...modalFormRef.current?.getFieldValue(), msgTempId: undefined, content: null })
          }
       },
      { name: 'cfgRiskRank', label: '风险等级', controlType: TYPE.SELECT, codeKey: 'RiskGradeType', disabled: isDisabled, rules: [RULE_REQUIRED] },
      { 
        name: 'untrueRoleIds', label: '通知角色', controlType: TYPE.SELECTALL, codeKey: 'emerRoles', rules: [RULE_REQUIRED],
        onChange: (value, option=[]) => {
          modalFormRef.current?.setFieldValue('roleIds', option.map(item => item.value))
        },
        optionTemplate: option => <>{option.label}</>
      },
      { 
        options: [],
        ...selectConfig('roleIds','产品类型'),
        selectmode: "multiple",
        mode: 'hidden'
    }, 
      { 
        name:'tempType', label:'通知模板类型', controlType:TYPE.SELECT, codeKey:'noticesTempType', rules: [RULE_REQUIRED],
        onChange: () => {
          const noticesTempType = modalFormRef.current?.getFieldValue?.('tempType')
          setIsInterior(noticesTempType === 'interior')
        }
      },

      isInterior ? {
        options: templates,
        ...selectConfig('msgTempId','通知模板'),
        rules: [RULE_REQUIRED],
        onFocus: () => getTemplateList(),
        onSelect: value => setTemplateContent(value, templates, modalFormRef)
      }: null,
      isInterior ? { name: 'content', label: "通知内容", controlType: TYPE.TEXTAREA, disabled:true, style: { height: 200 } } : null,
      { name: 'status', label: '状态', controlType: TYPE.SELECT, codeKey: 'status', rules: [RULE_REQUIRED] }
    ].filter(_ => _)
  }

    return {
      modalFormRef,
      modalFields,
      setIsDisabled,
      getTemplateList
    }
};

export { fields, GetColumns, useModalFields }